const { verifyAdminToken, verifyMiniappToken } = require('@shared/utils/jwt');
const User = require('@models/user');
const Admin = require('@models/admin');
const jwt = require('jsonwebtoken');
const { ApiResponse } = require('@shared/utils/response');
const jwtConfig = require('@config/jwt');

// 管理员认证中间件
exports.adminAuth = async (req, res, next) => {
  try {
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) {
      return res.json(ApiResponse.unauthorized('未登录'));
    }

    const decoded = jwt.verify(token, jwtConfig.admin.secret);
    if (!decoded) {
      return res.json(ApiResponse.unauthorized('token无效'));
    }

    const admin = await Admin.findByPk(decoded.id);
    if (!admin || admin.status === 0) {
      return res.json(ApiResponse.forbidden('账号已禁用'));
    }

    req.admin = admin;
    next();
  } catch (err) {
    if (err.name === 'JsonWebTokenError') {
      return res.json(ApiResponse.unauthorized('token无效'));
    }
    if (err.name === 'TokenExpiredError') {
      return res.json(ApiResponse.unauthorized('token已过期'));
    }
    next(err);
  }
};

// 小程序用户认证中间件
exports.userAuth = async (req, res, next) => {
  try {
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) {
      return res.json(ApiResponse.unauthorized('未登录'));
    }

    const decoded = jwt.verify(token, jwtConfig.miniapp.secret);
    if (!decoded) {
      return res.json(ApiResponse.unauthorized('token无效'));
    }

    const user = await User.findByPk(decoded.id);
    if (!user || user.status === 0) {
      return res.json(ApiResponse.forbidden('账号已禁用'));
    }

    req.user = user;
    next();
  } catch (err) {
    if (err.name === 'JsonWebTokenError') {
      return res.json(ApiResponse.unauthorized('token无效'));
    }
    if (err.name === 'TokenExpiredError') {
      return res.json(ApiResponse.unauthorized('token已过期'));
    }
    next(err);
  }
};

const verifyAdmin = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];

  if (!token) {
    return res.status(401).json(ApiResponse.fail(401, '未授权，请先登录'));
  }

  try {
    const decoded = jwt.verify(token, jwtConfig.admin.secret);
    req.admin = decoded;
    next();
  } catch (error) {
    return res.status(401).json(ApiResponse.fail(401, '无效的token，请重新登录'));
  }
};

// 用户身份验证中间件
exports.authMiddleware = async (req, res, next) => {
  try {
    // 获取请求头中的token
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({ code: 401, message: '未授权：缺少有效token' });
    }

    const token = authHeader.split(' ')[1];
    const decoded = jwt.verify(token, jwtConfig.secret);

    // 查询用户信息
    const user = await User.findByPk(decoded.id);
    if (!user) {
      return res.status(401).json({ code: 401, message: '未授权：用户不存在' });
    }

    if (user.status !== 1) {
      return res.status(403).json({ code: 403, message: '账号已被禁用' });
    }

    // 将用户信息添加到请求对象
    req.user = user;
    next();
  } catch (error) {
    return res.status(401).json({ code: 401, message: '未授权：无效的token' });
  }
};

// 小程序用户身份验证中间件
exports.miniappAuthMiddleware = async (req, res, next) => {
  try {
    // 获取请求头中的token
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({ code: 401, message: '未授权：缺少有效token' });
    }

    const token = authHeader.split(' ')[1];
    const decoded = jwt.verify(token, jwtConfig.miniapp.secret);

    // 查询用户信息
    const user = await User.findByPk(decoded.id);
    if (!user) {
      return res.status(401).json({ code: 401, message: '未授权：用户不存在' });
    }

    if (user.status !== 1) {
      return res.status(403).json({ code: 403, message: '账号已被禁用' });
    }

    // 将用户信息添加到请求对象
    req.user = user;
    next();
  } catch (error) {
    return res.status(401).json({ code: 401, message: '未授权：无效的token' });
  }
};

// 管理员身份验证中间件
exports.adminAuthMiddleware = async (req, res, next) => {
  try {
    // 获取请求头中的token
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({ code: 401, message: '未授权：缺少有效token' });
    }

    const token = authHeader.split(' ')[1];
    const decoded = jwt.verify(token, jwtConfig.admin.secret);

    // 查询管理员信息
    const admin = await Admin.findByPk(decoded.id);
    if (!admin) {
      return res.status(401).json({ code: 401, message: '未授权：管理员不存在' });
    }

    if (admin.status !== 1) {
      return res.status(403).json({ code: 403, message: '账号已被禁用' });
    }

    // 将管理员信息添加到请求对象
    req.admin = admin;
    next();
  } catch (error) {
    return res.status(401).json({ code: 401, message: '未授权：无效的token' });
  }
};

module.exports = {
  adminAuth: exports.adminAuth,
  userAuth: exports.userAuth,
  verifyAdmin,
  authMiddleware: exports.authMiddleware,
  miniappAuthMiddleware: exports.miniappAuthMiddleware,
  adminAuthMiddleware: exports.adminAuthMiddleware
}; 